<?php

//Talks to mySQL server through queries.
class DB_Functions {
 
    private $db;
 
    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }
 
    // destructor
    function __destruct() {
 
    }
 
    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($userName, $full, $phone, $email, $password, $img, $gender, $sec, $ans, $maj) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO members (username, password, full, phone, email, img, gender, sec, ans, major) VALUES ('$userName', '$password', '$full', '$phone', '$email', '$img', '$gender', '$sec', '$ans', '$maj')");
        // check for successful store
        if ($result) {
            // get user details
            $result = mysql_query("SELECT * FROM members WHERE username = '$userName'");
            // return user details
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    }
	
	//Store image name in database
	public function storeImg($userName, $img){
		
		$result = mysql_query("UPDATE members SET img = '$img' WHERE username = '$userName'");
		
		if ($result) {
		
            // get user details
            $result = mysql_query("SELECT * FROM  members WHERE  username =  '$userName'");
			
            // return user details
            return $result;
			
        } 
		else {
            return false;
        }
	}
 
    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {
        $result = mysql_query("SELECT * FROM members WHERE username = '$email'") or die(mysql_error());
        // check for result
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
			
            if ($password == $result['password']) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return false;
        }
    }
 
    /**
     * Check user is existed or not
     */
    public function isUserExisted($userName) {
        $result = mysql_query("SELECT email from members WHERE username = '$userName'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return true;
        } else {
            // user not existed
            return false;
        }
    }
	
	//Check if a class exists in the database
	 public function classExisted($userName, $course, $term) {
        $result = mysql_query("SELECT username FROM class WHERE username = '$userName' AND cname = '$course' AND term = '$term'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return true;
        } else {
            // user not existed
            return false;
        }
    }
	
	//Add a class to the database
	public function addClass($username, $term, $course, $grade){
	
		$result =  mysql_query("INSERT INTO class (cname, username, term, tutoring, grade) VALUES ('$course', '$username', '$term', 0, '$grade')");
		
		if ($result) {
			$result = mysql_query("SELECT * FROM class WHERE username = '$username'");
			
			return $result;
		}
		else
			return false;
	
	}
	
	//add a tutor session to the database
	public function addSession($tutor, $tutoree, $date, $time, $subject, $location, $other, $status){
		
		$result =  mysql_query("INSERT INTO sessions (date, time, location, subject, other, tutor, tutoree, status) VALUES ('$date', '$time', '$location', '$subject', '$other', '$tutor', '$tutoree', '$status')");
		
		if ($result) {
			return true;
		}
		else
			return false;
			
	}
	
	//Retrieve all user info
	public function retrieveInfo($un){
		
		$result = mysql_query("SELECT * FROM members WHERE username = '$un'");
        
		//return user details
        return mysql_fetch_array($result);
	
	}
	
	//Update a user status to tutor in the database
	public function updateTutor($un, $cname, $term, $tutor){
	
		$result = mysql_query("UPDATE class SET tutoring = '$tutor' WHERE username = '$un' AND cname = '$cname' AND term = '$term'");
		
		return $result;
	
	}
	
	//Retrieve all tutor notifications
	public function retreiveNotifications($un, $type){
		
		if ($type != 5){
			$result = mysql_query("SELECT * FROM sessions WHERE (tutor = '$un' OR tutoree = '$un') AND status = '$type'");
		}
		else
			$result = mysql_query("SELECT * FROM sessions WHERE (tutor = '$un' OR tutoree = '$un')");
		
		return $result;

	}
	
	//Update a user rating
	public function updateRating($un, $rating, $count){
		
		$result = mysql_query("UPDATE members SET rating = '$rating', numRatings = '$count' WHERE username = '$un'");
		
		return $result;
		
	}
	
	//Update a session
	public function updateSession($id, $value){
	
		$result = mysql_query("UPDATE sessions SET status = '$value' WHERE id = '$id'");
		
		return $result;
	}
	
	//Update a session info
	public function updateSessionInfo($id, $tutor, $tutoree, $date, $time, $subject, $location, $other, $status){
		
		$result = mysql_query("UPDATE sessions SET tutor = '$tutor', date = '$date', tutoree = '$tutoree', time = '$time', subject = '$subject', location = '$location', other = '$other', status = '$status' WHERE id = '$id'");
		
		return $result;
		
	}
	
	//Retreive all user messages
	public function retreiveMessages($un, $status){
	
		$result = mysql_query("SELECT * FROM message WHERE user = '$un' and status = '$status'");
		
		return $result;
	}
	
	//Delete a session from the database
	public function deleteSession($id){
	
		$result = mysql_query("DELETE FROM sessions WHERE id = '$id'");
		
		return $result;
	}
	
	//Add a message to the database
	public function addMessage($sender, $user, $mess, $sub){
	
		$new = "new";
		
		$result =  mysql_query("INSERT INTO message (user, sender, message, status, subject) VALUES ('$user', '$sender', '$mess', '$new', '$sub')");
		
		if ($result) {
			return true;
		}
		else
			return false;
	
	}
	
	//Update a message in the database
	public function updateMessage($id){
		
		$old = "old";
		
		$result = mysql_query("UPDATE message SET status = '$old' WHERE id = '$id'");
		
		return $result;
		
	}
	
	//Update class info
	public function updateClass($id, $grade, $tutoring){
		
		$old = "old";
		
		$result = mysql_query("UPDATE class SET tutoring = '$tutoring', grade = '$grade' WHERE id = '$id'");
		
		return $result;
		
	}
	
	//Delete a message
	public function deleteMessage($id){
	
		$result = mysql_query("DELETE FROM message WHERE id = '$id'");
		
		return $result;
	}
	
	//Update user profile
	public function updateProfile($un, $full, $phone, $email, $password, $security, $ans, $maj){
		
		$result = mysql_query("UPDATE members SET full = '$full', phone = '$phone', email = '$email', password = '$password', sec = '$security', ans = '$ans', major = '$maj' WHERE username = '$un'");
		
		//$result = mysql_query("UPDATE members SET full = '$full' WHERE username = '$un'");
		
		return $result;
	}
	
	//Retrieve all user courses
	public function retrieveAllCourses($un){
	
		$result = mysql_query("SELECT * FROM class WHERE username = '$un'");
		
		return $result;
	}
	
	//Retrieve all tutors
	public function retrieveTutors($cname, $term){
	
		$one = "1";
		
		$result = mysql_query("SELECT * FROM class WHERE cname = '$cname' AND tutoring = '$one'");
		
		return $result;
	}
 
    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {
 
        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }
 
    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {
 
        $hash = base64_encode(sha1($password . $salt, true) . $salt);
 
        return $hash;
    }
 
}
 
?>